package com.qianbao.qianbaobusiness.ui.home;

import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.androidbase.base.BaseApplication;
import com.androidbase.base.mvp.RxMvpPresenter;
import com.androidbase.dagger.help.GlideApp;
import com.androidbase.utils.DeviceUuid;
import com.androidbase.utils.DigestUtils;
import com.androidbase.utils.FileUtils;
import com.androidbase.utils.ImageUtils;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.StringUtils;
import com.androidbase.utils.ThreadUtils;
import com.baseandroid.config.Global;
import com.baseandroid.config.MyApi;
import com.baseandroid.jpush.JPushBizutils;
import com.baseandroid.retrofit.RxObserver;
import com.baseandroid.retrofit.json.Data;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.qianbao.qianbaobusiness.json.AlphaZone;
import com.qianbao.qianbaobusiness.json.ChannelBean;
import com.qianbao.qianbaobusiness.json.MerchantAdvertsBean;
import com.qianbao.qianbaobusiness.json.UnPayinfoParentBean;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.inject.Inject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author: Routee
 * @date 2018/6/11
 * @mail wangc4@qianbaocard.com
 * ------------1.本类由Routee开发,阅读、修改时请勿随意修改代码排版格式后提交到git。
 * ------------2.阅读本类时，发现不合理请及时指正.
 * ------------3.如需在本类内部进行修改,请先联系Routee,若未经同意修改此类后造成损失本人概不负责。
 */
public class HomePresenter extends RxMvpPresenter<HomeView> {

    MyApi mApi;

    @Inject
    public HomePresenter(MyApi api) {
        mApi = api;
    }

    public void getAppPushconfig() {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("cityCode", StringUtils.isEmpty(Global.getMyLocation()
                                                             .getCityCode()) ? "" : Global.getMyLocation().getCityCode());
        mApi.getAppPushconfig(paramMap)
                .compose(RxUtils.<Data<ChannelBean>>applySchedulersLifeCycle(getView()))
                .subscribe(new RxObserver<Data<ChannelBean>>() {
                    @Override
                    public void onNext(Data<ChannelBean> channelBeanData) {
                        if (RxObserver.checkJsonCode(channelBeanData, false)) {
                            getView().onAppPushConfig(true, channelBeanData.getResult());
                        } else {
                            getView().onAppPushConfig(false, null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        getView().onAppPushConfig(false, null);
                    }
                });

    }

    public void updataAppPushconfig(String channel) {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("type", "01");
        paramMap.put("audienceChannel", channel);
        if (channel.equals("1")) {
            paramMap.put("audience", PushServiceFactory.getCloudPushService()
                                             .getDeviceId());
        } else {
            paramMap.put("audience", DigestUtils.md5Hex(Global.getUserInfoBean()
                                                                .getUser()
                                                                .getMobile() + DeviceUuid.getDeviceId(Global.getContext())));
            /*--适用切换账号--*/
            JPushBizutils.initJPush();
        }
        mApi.updataAppPushconfig(paramMap)
                .compose(RxUtils.<Data>applySchedulersLifeCycle(getView()))
                .subscribe();
    }

    public void getAppAlphaZone() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("classcode", "BUSINESS_OUTSIDE_PARAM");
        mApi.getAppAlphaZone(hashMap)
                .compose(RxUtils.<Data<AlphaZone>>applySchedulersLifeCycle(getView()))
                .subscribe(new RxObserver<Data<AlphaZone>>() {
                    @Override
                    public void onNext(Data<AlphaZone> alphaZoneData) {
                        if (RxObserver.checkJsonCode(alphaZoneData, false)) {
                            Global.setAlphaZone(alphaZoneData.getResult()
                                                        .getAlphacitycode());
                            // 处理灰度与跳转
                            getView().AlphaZone();
                        }
                    }
                });
    }

    public void getAppAdvertImg() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("positionId", "20180621119455");
        mApi.getAppAdvertImg(hashMap)
                .compose(RxUtils.<Data<MerchantAdvertsBean>>applySchedulersLifeCycle(getView()))
                .subscribe(new RxObserver<Data<MerchantAdvertsBean>>() {
                    @Override
                    public void onNext(Data<MerchantAdvertsBean> merchantAdvertsBeanData) {
                        if (RxObserver.checkJsonCode(merchantAdvertsBeanData, false)) {
                            if (merchantAdvertsBeanData.getResult()
                                        .getAdverts() != null && merchantAdvertsBeanData.getResult()
                                                                         .getAdverts()
                                                                         .size() > 0) {
                                MerchantAdvertsBean.AdvertsBean advertsBean = merchantAdvertsBeanData
                                                                                      .getResult()
                                                                                      .getAdverts()
                                                                                      .get(0);
                                if (StringUtils.isEmpty(advertsBean.getImageUrl())) {
                                    try {
                                        if (FileUtils.isExistingFile(new File(Global.getAdvertFilePath()))) {
                                            FileUtils.delete(Global.getAdvertFilePath());
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    GlideApp.with(Global.getContext())
                                            .load(advertsBean.getImageUrl())
                                            .into((SimpleTarget) new SimpleTarget<BitmapDrawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull BitmapDrawable resource, @Nullable Transition<? super BitmapDrawable> transition) {
                                                    if (!resource.getBitmap()
                                                                 .isRecycled()) {
                                                        ThreadUtils.newSingleThreadExecutor("")
                                                                .execute(new Runnable() {
                                                                    @Override
                                                                    public void run() {
                                                                        try {
                                                                            String dirstring = BaseApplication
                                                                                                       .getAppComponent()
                                                                                                       .getCacheDir()
                                                                                                       .getAbsolutePath() + "/advert/";
                                                                            String filepath = ImageUtils
                                                                                                      .saveBitmap2File(dirstring, resource
                                                                                                                                          .getBitmap());
                                                                            if (FileUtils.isExistingFile(new File(Global
                                                                                                                          .getAdvertFilePath()))) {
                                                                                FileUtils.delete(Global
                                                                                                         .getAdvertFilePath());
                                                                            }
                                                                            Global.setAdvertFilePath(filepath);
                                                                        } catch (IOException e) {
                                                                            e.printStackTrace();
                                                                        }
                                                                    }
                                                                });
                                                    }
                                                }
                                            });
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 获取未缴纳押金
     *
     * @param afterId
     */
    public void getMerchantPaymentInfo(String afterId) {
                mApi.getMerchantPaymentInfo(afterId)
                        .compose(RxUtils.applySchedulersLifeCycle(getView()))
                        .subscribe(new Observer<Data<UnPayinfoParentBean>>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Data<UnPayinfoParentBean> stringData) {
                                if (RxObserver.checkJsonCode(stringData, false)) {
                                    getView().hasUnPay(stringData.getResult());
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
    }
}
